/**
 * @ClassName: SysUserServiceImpl
 * @Description
 * @Author maozhi
 * @Date 2021/3/22
 * @Time 14:45
 */

package com.universityJob.modules.data.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.universityJob.common.utils.*;
import com.universityJob.modules.data.dao.DataUserDao;
import com.universityJob.modules.data.entity.DataRecEntity;
import com.universityJob.modules.data.entity.DataUserEntity;
import com.universityJob.modules.data.service.DataUserService;

import com.universityJob.modules.sys.entity.SysUserEntity;


import net.sf.json.JSONArray;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 *
 *
 * @author Administrator
 */
@Service("dataUserService")
public class DataUserServiceImpl extends ServiceImpl<DataUserDao, DataUserEntity> implements DataUserService {
    @Autowired
    private Upload upload;
    @Autowired
    private ExportExcel exportExcel;
    @Autowired
    private FormatData formatData;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("username");
        IPage<DataUserEntity> page = this.page(
                new Query<DataUserEntity>().getPage(params),
                new QueryWrapper<DataUserEntity>()
                        .like(StringUtils.isNotBlank(username), "username", username)
        );

        return new PageUtils(page);
    }


    @Override
    public DataUserEntity queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }

    @Override
    @Transactional
    public R saveUser(DataUserEntity user) {
        if (StringUtils.isBlank(user.getEmail()) || StringUtils.isBlank(user.getGender()) || StringUtils.isBlank(user.getMajor())
                || StringUtils.isBlank(user.getMobile()) || StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getUsername())
                || StringUtils.isBlank(user.getSource()) || StringUtils.isBlank(user.getPassword())) {
            return R.error("所有信息都不能为空！");
        }
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        this.save(user);
        return R.ok();
    }

    @Override
    @Transactional
    public R update(DataUserEntity user) {
        if (StringUtils.isBlank(user.getEmail()) || StringUtils.isBlank(user.getGender()) || StringUtils.isBlank(user.getMajor())
                || StringUtils.isBlank(user.getMobile()) || StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getUsername())
                || StringUtils.isBlank(user.getSource())) {
            return R.error("所有信息都不能为空！");
        }
        if (!StringUtils.isBlank(user.getPassword())) {
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
        } else {
            user.setPassword(null);
        }
        this.updateById(user);
        return R.ok();
    }

    @Override
    public R deleteBatch(Long[] userId) {
        boolean remove = this.removeByIds(Arrays.asList(userId));
        if (remove) {
            return R.ok();
        }
        return R.error("删除出错，请联系管理员！");
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        DataUserEntity dataUserEntity = new DataUserEntity();
        dataUserEntity.setPassword(newPassword);
        return this.update(dataUserEntity,
                new QueryWrapper<DataUserEntity>().eq("user_id", userId).eq("password", password));
    }

    @Override
    public R uploadExcel(MultipartFile file, String fileName) {
        return null;
    }

    @Override
    public int exportStatisticsReport(HttpServletResponse response, Map<String, Object> params) {
        //获取数据
        List<Map<String, Object>> maps = baseMapper.selectMaps(null);
        for (Map m : maps) {
            String source = MapUtils.getString(m, "source", "");
            String employmentZones = MapUtils.getString(m, "employmentZones", "");
            String municipalityDirectly = MapUtils.getString(m, "municipalityDirectly", "");
            String[] sources = source.split(",");
            String[] employmentZoness = employmentZones.split(",");
            String[] municipalityDirectlys = municipalityDirectly.split(",");
            if (sources[0].matches("[0-9]{1,}")) {
                String s = formatData.codeToText(sources);
                m.put("source", s);
            }
            if (employmentZoness[0].matches("[0-9]{1,}")) {
                String s = formatData.codeToText(employmentZoness);
                m.put("employmentZones", s);
            }
            if (municipalityDirectlys[0].matches("[0-9]{1,}")) {
                String s = formatData.codeToText(municipalityDirectlys);
                m.put("municipalityDirectly", s);
            }
            String gender = formatData.formateSex(MapUtils.getString(m, "gender", ""));
            m.put("gender", gender);
            String status = formatData.formateStatus(MapUtils.getString(m, "status", ""));
            m.put("status", status);
        }
        int i = exportExcel.excelInit(maps, response, params);
        if (i == 0) {
            //excel导出失败！
            return 0;
        }
        //以上均为数据准备,下面开始调用导出excel工具类
        return 1;
    }

    @Override
    public int inputExcel(HttpServletResponse response, Map<String, Object> params) {
        String users = MapUtils.getString(params, "user", "");
        int count = 0;
        List<DataUserEntity> list = JSON.parseArray(users, DataUserEntity.class);//list json字符串转
        for (DataUserEntity user : list) {
            user.setSource(formatData.textToCode(user.getSource()));
            user.setEmploymentZones(formatData.textToCode(user.getEmploymentZones()));
            user.setMunicipalityDirectly(formatData.textToCode(user.getMunicipalityDirectly()));
            user.setStatus(formatData.formateStatus(user.getStatus()));
            user.setGender(formatData.formateSex(user.getGender()));
            try {
                baseMapper.insert(user);
                count += 1;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return count;
    }
}
